package com.example.himalaya.view_component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.example.himalaya.R;

@SuppressLint("AppCompatCustomView")
public class LoadingView extends ImageView {

    // Variable
    private int rotateDegree = 0;

    private boolean mNeedRotate = false;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 设置图片
        setImageResource(R.mipmap.loading);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /**
         * 第一个参数：旋转角度
         * 第二个： 旋转的x 坐标
         * 第二个： 旋转的y 坐标
         */
        canvas.rotate(rotateDegree, getWidth() / 2, getHeight() /2);
        super.onDraw(canvas);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        mNeedRotate = true;

        // 绑定到window 的时候
        post(new Runnable() {
            @Override
            public void run() {
                rotateDegree += 30;

                rotateDegree = rotateDegree <= 360 ? rotateDegree : 0;

                invalidate();

                if(mNeedRotate) {
                    // 是否继续旋转
                    postDelayed(this, 100);
                }

            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 从window中解绑 的时候
        mNeedRotate = false;
    }
}
